package com.gobang.modules.match;

import com.gobang.modules.message.MsgHandler;
import com.gobang.entity.User;
import com.gobang.modules.message.MessageService;
import com.gobang.modules.player.PlayerService;
import com.gobang.modules.login.UserService;
import com.gobang.proto.GameProto.*;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 匹配控制器
 * 处理匹配相关的消息
 */
@Slf4j
@Component
public class MatchController {

    @Autowired
    private MatchService matchService;
    @Autowired
    private PlayerService playerService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    /**
     * 处理匹配请求
     * 注意：登录验证已在 WebSocketHandler 中统一处理，此处无需再验证
     */
    @MsgHandler(MessageType.MATCH_REQUEST)
    public void onMatchRequest(ChannelHandlerContext ctx, MatchRequest request) {
        // 从 Channel 获取真实用户ID（已在 WebSocketHandler 验证过登录状态）
        Long userId = playerService.getUserId(ctx);

        User user = userService.getUserById(userId);
        if (user == null) {
            messageService.sendError(ctx, 404, "用户不存在");
            return;
        }

        MatchResponse response = matchService.joinMatch(user);
        messageService.sendMessage(ctx, MessageType.MATCH_RESPONSE, response.toByteArray());
    }

    /**
     * 处理取消匹配请求
     * 注意：登录验证已在 WebSocketHandler 中统一处理，此处无需再验证
     */
    @MsgHandler(MessageType.CANCEL_MATCH)
    public void onCancelMatch(ChannelHandlerContext ctx, CancelMatchRequest request) {
        // 从 Channel 获取真实用户ID（已在 WebSocketHandler 验证过登录状态）
        Long userId = playerService.getUserId(ctx);
        
        matchService.cancelMatch(userId);
        
        // 发送取消匹配响应
        CancelMatchResponse response = CancelMatchResponse.newBuilder()
                .setSuccess(true)
                .setMessage("已取消匹配")
                .build();
        messageService.sendMessage(ctx, MessageType.CANCEL_MATCH_RESPONSE, response.toByteArray());
    }
}
